package com.hngates.architecture.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hngates.architecture.domain.*;
import com.hngates.architecture.domain.vo.ProjectComplexInfoVO;
import com.hngates.architecture.service.*;
import com.hngates.common.annotation.Log;
import com.hngates.common.core.controller.BaseController;
import com.hngates.common.core.domain.AjaxResult;
import com.hngates.common.core.page.TableDataInfo;
import com.hngates.common.enums.BusinessType;
import com.hngates.common.utils.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 项目（工地）Controller
 *
 * @author jwhe
 * @date 2022-07-04
 */
@Controller
@RequestMapping("/architecture/project")
public class ArcProjectController extends BaseController {
    private String prefix = "architecture/project";

    @Autowired
    private IArcProjectService arcProjectService;
    @Autowired
    private IArcBuilderCompanyService arcBuilderCompanyService;
    @Autowired
    private IArcConstructContractService arcConstructContractService;
    @Autowired
    private IArcLabourCompanyService arcLabourCompanyService;
    @Autowired
    private IArcLabourContractService arcLabourContractService;
    @Autowired
    private IArcLabourSubCompanyService arcLabourSubCompanyService;
    @Autowired
    private IArcLabourSubCompanyDetailsService arcLabourSubCompanyDetailsService;
    @Autowired
    private IArcProjectBuilderRelService arcProjectBuilderRelService;

    @RequiresPermissions("architecture:project:view")
    @GetMapping()
    public String project() {
        return prefix + "/project";
    }

    /**
     * 查询项目（工地）列表
     */
    @RequiresPermissions("architecture:project:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ArcProject arcProject) {
        startPage();
        List<ArcProject> list = arcProjectService.selectArcProjectList(arcProject);
        return getDataTable(list);
    }

    /**
     * 导出项目（工地）列表
     */
    @RequiresPermissions("architecture:project:export")
    @Log(title = "项目（工地）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ArcProject arcProject) {
        List<ArcProject> list = arcProjectService.selectArcProjectList(arcProject);
        ExcelUtil<ArcProject> util = new ExcelUtil<ArcProject>(ArcProject.class);
        return util.exportExcel(list, "项目（工地）数据");
    }

    /**
     * 新增项目（工地）
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存项目（工地）
     */
    @RequiresPermissions("architecture:project:add")
    @Log(title = "项目（工地）", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ArcProject arcProject) {
        return toAjax(arcProjectService.insertArcProject(arcProject));
    }

    /**
     * 修改项目（工地）
     */
    @RequiresPermissions("architecture:project:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        ArcProject arcProject = arcProjectService.selectArcProjectById(id);
        mmap.put("arcProject", arcProject);
        return prefix + "/edit";
    }

    /**
     * 修改保存项目（工地）
     */
    @RequiresPermissions("architecture:project:edit")
    @Log(title = "项目（工地）", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ArcProject arcProject) {
        return toAjax(arcProjectService.updateArcProject(arcProject));
    }

    /**
     * 删除项目（工地）
     */
    @RequiresPermissions("architecture:project:remove")
    @Log(title = "项目（工地）", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(arcProjectService.deleteArcProjectByIds(ids));
    }


    /**
     * 下载模板
     *
     * @return
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate(HttpServletRequest request, HttpServletResponse response) {


        String fileName = "template/工地信息导入.xlsx";
        return AjaxResult.success(fileName);

        /*ServletOutputStream outputStream = null;
        BufferedInputStream inputStream = null;
        try {
            String pdfPath = "static/template/工地信息导入.xlsx";
            String fileName = "工地信息导入.xlsx";

            if (FileUtil.exist(pdfPath)) {
                response.setCharacterEncoding("utf-8");
                response.addHeader("Pargam", "no-cache");
                response.addHeader("Cache-Control", "no-cache");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
                outputStream = response.getOutputStream();
                inputStream = FileUtil.getInputStream(pdfPath);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }

        } catch (Exception e) {
            logger.error("下载模板时异常", e);
            return AjaxResult.error("下载时异常");
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
        return AjaxResult.success("下载成功");*/
    }

    /**
     * 导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */

    @RequiresPermissions("architecture:project:import")
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importInformation(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ProjectComplexInfoVO> util = new ExcelUtil<>(ProjectComplexInfoVO.class);
        List<ProjectComplexInfoVO> projectComplexInfoVOS = util.importExcel(file.getInputStream(), 1);
        //todo:临时在此处理数据
        if (projectComplexInfoVOS == null || projectComplexInfoVOS.isEmpty()) {
            return AjaxResult.success("ok");
        }
        for (ProjectComplexInfoVO item : projectComplexInfoVOS) {
            ArcProject project = new ArcProject();
            project.setProjectNo(item.getProjectNo())
                    .setProjectName(item.getProjectName())
                    .setProjectStatus(item.getProjectStatus());

            ArcProject dbProject = arcProjectService.selectArcProjectByName(project.getProjectName());
            if (dbProject == null) {
                arcProjectService.insertArcProject(project);
            } else {
                project.setId(dbProject.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(project, dbProject);
                    arcProjectService.updateArcProject(dbProject);
                }
            }

            //建设单位
            ArcBuilderCompany builderCompany = new ArcBuilderCompany();
            builderCompany.setCompanyName(item.getBuilderCompanyName())
                    .setManagerName(item.getBuilderManagerName())
                    .setManagerPhone(item.getBuilderManagerPhone())
                    .setGuaranteeAmount(item.getBuilderGuaranteeAmount())
                    .setGuaranteeAmountFree(item.getBuilderGuaranteeAmountFree())
                    .setGuaranteePeriod(item.getBuilderGuaranteePeriod());
            ArcBuilderCompany dbBuilderCompany = arcBuilderCompanyService.selectArcBuilderCompanyByName(builderCompany.getCompanyName());
            if (dbBuilderCompany == null) {
                arcBuilderCompanyService.insertArcBuilderCompany(builderCompany);
            } else {
                builderCompany.setId(dbBuilderCompany.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(builderCompany, dbBuilderCompany);
                    arcBuilderCompanyService.updateArcBuilderCompany(dbBuilderCompany);
                }
            }
            //关系绑定
            boolean exists = arcProjectBuilderRelService.selectArcProjectBuilderRelById(project.getId(), builderCompany.getId());
            if (!exists) {
                ArcProjectBuilderRel projectBuilderRel = new ArcProjectBuilderRel();
                projectBuilderRel.setProjectId(project.getId());
                projectBuilderRel.setBuilderId(builderCompany.getId());
                arcProjectBuilderRelService.insertArcProjectBuilderRel(projectBuilderRel);
            }

            //施工单位
            //单位名称	负责人(SG)	电话(SG)	籍贯(SG)	支付保函金额(SG)	保函可用余额(SG)	保函有效期(SG)
            ArcLabourCompany labourCompany = new ArcLabourCompany();
            labourCompany.setCompanyName(item.getLabourCompanyName())
                    .setManagerName(item.getLabourManagerName())
                    .setManagerPhone(item.getLabourManagerPhone())
                    .setNativePlace(item.getLabourNativePlace())
                    .setGuaranteePeriod(item.getLabourGuaranteePeriod())
                    .setGuaranteeAmountFree(item.getLabourGuaranteeAmountFree())
                    .setPaidGuaranteeAmount(item.getLabourPaidGuaranteeAmount());
            ArcLabourCompany dbLabourCompany = arcLabourCompanyService.selectArcLabourCompanyByName(labourCompany.getCompanyName());
            if (dbLabourCompany == null) {
                arcLabourCompanyService.insertArcLabourCompany(labourCompany);
            } else {
                labourCompany.setId(dbLabourCompany.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(labourCompany, dbLabourCompany);
                    arcLabourCompanyService.updateArcLabourCompany(dbLabourCompany);
                }
            }

            //施工合同
            //合同金额(SH)	支付方式(SH)	拖欠工程款金额(SH)	计划支付日期(SH)
            ArcConstructContract constructContract = new ArcConstructContract();
            constructContract.setContractAmount(item.getBuilderContractAmount())
                    .setPaymentArrears(item.getBuilderPaymentArrears())
                    .setPayMethod(item.getBuilderPayMethod())
                    .setPlanPayDate(item.getBuilderPlanPayDate())
                    .setProjectId(project.getId())
                    .setLabourId(labourCompany.getId())
                    .setBuilderId(builderCompany.getId())
                    .setRemark(item.getBuilderRemarks());

            ArcConstructContract dbConstructContract = arcConstructContractService.selectArcConstructContractById(project.getId(), builderCompany.getId(), labourCompany.getId());
            if (dbConstructContract == null) {
                arcConstructContractService.insertArcConstructContract(constructContract);
            } else {
                constructContract.setId(dbConstructContract.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(constructContract, dbConstructContract);
                    arcConstructContractService.updateArcConstructContract(dbConstructContract);
                }
            }

            //劳务分包单位
            //单位名称(FB)	工人组成(FB)	负责人(FB)	电话(FB)	籍贯(FB)
            ArcLabourSubCompany labourSubCompany = new ArcLabourSubCompany();
            labourSubCompany.setCompanyName(item.getLabourSubCompanyName())
                    .setManagerName(item.getLabourSubManagerName())
                    .setManagerPhone(item.getLabourSubManagerPhone())
                    .setNativePlace(item.getLabourSubNativePlace())
                    .setWorkerCombin(item.getLabourSubWorkerCombin());

            ArcLabourSubCompany dbLabourSubCompany = arcLabourSubCompanyService.selectArcLabourSubCompanyByName(labourSubCompany.getCompanyName());
            if (dbLabourSubCompany == null) {
                arcLabourSubCompanyService.insertArcLabourSubCompany(labourSubCompany);
            } else {
                labourSubCompany.setId(dbLabourSubCompany.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(labourSubCompany, dbLabourSubCompany);
                    arcLabourSubCompanyService.updateArcLabourSubCompany(dbLabourSubCompany);
                }
            }
            ArcLabourSubCompanyDetails labourSubCompanyDetails = new ArcLabourSubCompanyDetails();
            labourSubCompanyDetails.setRepresentPhone(item.getLabourSubRepresentPhone())
                    .setRepresentWorker(item.getLabourSubRepresentWorker())
                    .setSubLabourId(labourSubCompany.getId())
                    .setWagesArrearsAmount(item.getLabourSubWagesArrearsAmount())
                    .setWorkerNumberArrears(item.getLabourSubWorkerNumberArrears())
                    .setWorkerSource(item.getLabourSubWorkerSource());
            ArcLabourSubCompanyDetails dbLabourSubCompanyDetails = arcLabourSubCompanyDetailsService.selectArcLabourSubCompanyDetailsBySubLabourId(labourSubCompany.getId());
            if (dbLabourSubCompanyDetails == null) {
                arcLabourSubCompanyDetailsService.insertArcLabourSubCompanyDetails(labourSubCompanyDetails);
            } else {
                labourSubCompanyDetails.setId(dbLabourSubCompanyDetails.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(labourSubCompanyDetails, dbLabourSubCompanyDetails);
                    arcLabourSubCompanyDetailsService.updateArcLabourSubCompanyDetails(dbLabourSubCompanyDetails);
                }
            }


            //劳务合同
            //合同金额(LH)	支付方式(LH)	拖欠工程款金额(LH)	计划支付日期(LH)
            ArcLabourContract labourContract = new ArcLabourContract();
            labourContract.setContractAmount(item.getLabourContractAmount())
                    .setPaymentArrears(item.getLabourPaymentArrears())
                    .setPayMethod(item.getLabourPayMethod())
                    .setPlanPayDate(item.getLabourPlanPayDate())
                    .setProjectId(project.getId())
                    .setLabourId(labourCompany.getId())
                    .setSubLabourId(labourSubCompany.getId())
                    .setRemark(item.getLabourRemarks());
            ArcLabourContract dbLabourContract = arcLabourContractService.selectArcLabourContractById(project.getId(), labourCompany.getId(), labourSubCompany.getId());
            if (dbLabourContract == null) {
                arcLabourContractService.insertArcLabourContract(labourContract);
            } else {
                labourContract.setId(dbLabourContract.getId());
                if (updateSupport) {
                    BeanUtil.copyProperties(labourContract, dbLabourContract);
                    arcLabourContractService.updateArcLabourContract(dbLabourContract);
                }
            }

        }


        return AjaxResult.success();

    }

}
